export const updateurl = 'http://app.bukaa.cn/app-update/update.json';
export const amap_key = '69ee2f21ef46890bdd6a20b1615cc062';

// 管理账号信息
const USERS_KEY = 'USERS_KEY';
const STATE_KEY = 'STATE_KEY';

const getUsers = function () {
    var userInfo = uni.getStorageSync('userInfo');
    if(userInfo){
    	return userInfo;
    }
	var token = uni.getStorageSync('token');
	if(token){
		getCurrentUser(token);
	}
}

const getToken = function(){
	var token = uni.getStorageSync('token');
	return token;
}

const syncRequest = async function (requestUrl, data) {  
	let err,res;  
	[err,res] = await uni.request({  
		url: requestUrl,  
		data: data
	});
	console.log("数据：",err,res);  
	if(res.statusCode === 200){
		return res;
	}
}

const getCurrentUser =  function(token){
	if(!token)
		return;
	var res = syncRequest('https://bukaa.cn/api-admin/user/currentUser', {"Authorization":token});
	if(res && res.data){
		uni.setStorageSync('userInfo', res.data.data)
	}
}

const addUser = function (userInfo) {
    let users = getUsers();
    users.push({
        account: userInfo.account,
        password: userInfo.password
    });
    uni.setStorageSync(USERS_KEY, JSON.stringify(users));
}

const loginOut = function(){
	uni.clearStorage();
}

const setDoubanAuth = function(doubanAuth){
	uni.setStorageSync("doubanAuth", doubanAuth);
}

const getDoubanAuth = function(){
	return uni.getStorageSync("doubanAuth");
}
// 创建下载任务
const createDownload = function(url) {
	var plus = plus || null;
	if(plus && plus.downloader){
		createDownloadPlus(url);
	}else{
		createDownloadWeb(url);
	}
};

const createDownloadPlus = function(url) {
	plus.nativeUI.toast("操作中，请稍后...");
	var dtask = plus.downloader.createDownload(url, {}, function(d, status){
		// 下载完成
		if(status == 200){ 
			plus.gallery.save(d.filename, function() {
				plus.nativeUI.toast("下载成功,文件已保存")
			}, function() {
				plus.nativeUI.toast("下载失败")
			});
		}
		uni.hideLoading();
	});
	//dtask.addEventListener("statechanged", onStateChanged, false);
	if(dtask)
		dtask.start(); 
};

const createDownloadWeb = function(url){
	uni.showLoading({
		title:'操作中，请稍后...'
	})
	uni.downloadFile({
		url: url,
		success: (e) => {
			uni.saveImageToPhotosAlbum({
				filePath: e.tempFilePath,
				success: (errMsg) => {
					console.log(JSON.stringify(errMsg));
					uni.showToast({
						icon: "none",
						title: "下载成功， 已保存到手机相册"
					})
				},
				fail: () => {
					uni.showToast({
						icon: "none",
						title: "保存到手机相册失败"
					})
				},
				complete() {
					uni.hideLoading();
				}
			});
		},
		fail: (e) => {
			uni.showToast({
				icon: "none",
				title: "下载失败，" + e.errMsg
			})
		},
		complete() {
			uni.hideLoading();
		}
	})
}

export default {
    getUsers,
    addUser,
	getToken,
	loginOut,
	setDoubanAuth,
	getDoubanAuth,
	createDownload
}
